package com.example.itcompanyinterview;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONObject;

import com.example.itcompanyinterview.container.CustomArrayAdapter;
import com.example.itcompanyinterview.container.MapListImageAndTextListAdapter;
import com.example.itcompanyinterview.object.Category;
import com.example.itcompanyinterview.object.Role;
import com.example.itcompanyinterview.object.SubCategory;
import com.example.itcompanyinterview.tools.CommonJsonParser;
import com.example.itcompanyinterview.tools.CommonUrlRequest;
import com.example.itcompanyinterview.tools.CustomTitleSetter;
import com.example.itcompanyinterview.tools.LoadingDialogHelper;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.content.Intent;
import android.util.Log;
import android.util.Pair;
import android.view.Menu;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class SubCategoryActivity extends Activity {
	private Category _category;
	private LoadingDialogHelper _loadingHelper;
	private CustomTitleSetter _titleBar;
	private Handler _messageHandler;
	
	private static String CATEGORY_CONTROLER = "SubCategory";
	private static String GET_SUBCATEGORY_ACTION = "GetSubCategory";
	private static int GET_SUBCATEGORY = 0x04;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
		setContentView(R.layout.activity_sub_category);
		this.Initialize();
		this.InitMessageHandler();
		this.getSubCategoryList();
	}
	
	private void Initialize() {
		Intent intent = this.getIntent();
		Bundle bundle = intent.getExtras();
		this._category = (Category)bundle.getSerializable("category");
		
		_titleBar = new CustomTitleSetter(this);
        _titleBar.setTitle(this._category.getName(), View.GONE, View.VISIBLE);
        
        this._loadingHelper = new LoadingDialogHelper(this);
        this.setSubCategoryClickListener();
	}

	private void InitMessageHandler() {
		this._messageHandler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				if (msg.what == GET_SUBCATEGORY) {
					_loadingHelper.closeLoadingDialog();
					String categoryJsonString = (String) msg.obj;
					if (categoryJsonString == null) {
						Toast.makeText(SubCategoryActivity.this, "获取信息失败，请检测网络",
								Toast.LENGTH_SHORT).show();
						return;
					}
					initCategoryList(categoryJsonString);
				}
				super.handleMessage(msg);
			}
		};
	}
	
	private void getSubCategoryList() {
		new Thread(new Runnable() {
			public void run() {
				List<Pair<String, String>> paramList = new ArrayList<Pair<String, String>>();
				CommonUrlRequest.setParam(paramList, "cid", String.valueOf(_category.getId()));
				String subCategoryJsonString = CommonUrlRequest
						.getControllerAndAction(
								SubCategoryActivity.CATEGORY_CONTROLER,
								SubCategoryActivity.GET_SUBCATEGORY_ACTION,
								paramList);
				Message m = _messageHandler.obtainMessage();
				m.obj = subCategoryJsonString;
				m.what = GET_SUBCATEGORY;
				_messageHandler.sendMessage(m);
			}
		}).start();
		this._loadingHelper.showLoadingDialog();
	}
	
	public void initCategoryList(String categoryJsonString) {
		try {
			ListView subCategoryListView = (ListView) this.findViewById(R.id.subcategorylist);
			JSONObject categoryJsonObj = CommonJsonParser
					.parseJsonObject(categoryJsonString);
			if (categoryJsonObj.getInt("err") != 0) {
				Toast.makeText(SubCategoryActivity.this,
						"发生了异常:" + categoryJsonObj.getString("msg"),
						Toast.LENGTH_LONG).show();
				return;
			}

			List<SubCategory> subCategoryList = new ArrayList<SubCategory>();

			JSONArray categoryJsonList = CommonJsonParser
					.parseJsonArray(categoryJsonObj.getString("value"));
			int subCategoryNum = categoryJsonList.length();
			for (int i = 0; i < subCategoryNum; i++) {
				JSONObject subCategoryObj = categoryJsonList.getJSONObject(i);
				int subCategoryId = subCategoryObj.getInt("id");
				String subCategoryName = subCategoryObj.getString("name");
				SubCategory sub_category = new SubCategory(subCategoryId, 
						this._category.getId(), subCategoryName);
				subCategoryList.add(sub_category);
			}
			CustomArrayAdapter<SubCategory> adapter = 
				new CustomArrayAdapter<SubCategory>(this, subCategoryList, subCategoryListView);
			/*
			ArrayAdapter<SubCategory> adapter = new ArrayAdapter<SubCategory>(this, 
					android.R.layout.simple_list_item_single_choice, subCategoryList);
			*/
			subCategoryListView.setAdapter(adapter);
		} catch (Exception e) {
			Log.e("InitRoleList", e.getMessage());
		}
	}
	
	public void setSubCategoryClickListener() {
		ListView subCategoryListView = (ListView) this.findViewById(R.id.subcategorylist);
		subCategoryListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View arg1, int pos,
					long id) {
				SubCategory category = (SubCategory)parent.getItemAtPosition(pos);
				Bundle bundle = new Bundle();
				bundle.putSerializable("subcategory", category);
				Intent intent = null;
				int cid = category.getCid();
				switch(cid) {
					case 1:
					case 3:
						intent = new Intent(SubCategoryActivity.this,
								ProblemListActivity.class);
						intent.putExtras(bundle);
						startActivity(intent);
						break;
					case 2:
					case 4:
					case 5:
						intent = new Intent(SubCategoryActivity.this,
								SubCategoryContentActivity.class);
						intent.putExtras(bundle);
						startActivity(intent);
						break;
				}
			}
		});
	}
}
